<template>
	<div class="e-sign">
		<component
			:is="elesignCode"
			ref="myRef"
			:datas="state.datas"
			:pen="state.pen"
			:color="state.color"
		/>
		<div class="btns">
			<div @click="onReset">重写</div>
			<div @click="onConfirm">确定</div>
		</div>
	</div>
</template>

<script setup>
import elesignCode from  'elesigncode/lib/core/elesigncode'
import { ref, reactive, defineEmits } from 'vue'
import { Toast } from 'vant'
import { imgUpload } from '@/service/api'

const myRef = ref(null)
const state = reactive({
	pen: 'default',
	datas: '',
	color: '#DB8920'
})

const emits = defineEmits(['update:modelValue'])

const dataURLtoFile = (dataurl, filename = 'sign.png') => {
	let arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n)
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n)
	}
	return new File([u8arr], filename, { type: mime })
}

const onConfirm = () => {
	let length = JSON.parse(myRef.value.getJson()).data.length
	if (length) {
		uploadFile(dataURLtoFile(myRef.value.toPng()))
	} else {
		Toast('请签名')
	}
}

const uploadFile = async (file) => {
	const form = new FormData()
	form.append('File', file)
	const result = await imgUpload(form)
	try {
		if (result) {
			emits('update:modelValue', result)
			Toast('签名成功。')
		}
	} catch (e) {
		Toast('签名上传失败，请稍后重试。')
	}
}

const onReset = () => {
	// 官方重置方法不好用 撤回上一步好使  判断写了多少笔，就撤回多少次
	let length = JSON.parse(myRef.value.getJson()).data.length
	for (var i = 0; i < length; i++) {
		myRef.value.undo()
	}
}

</script>

<style scoped lang="less">
.e-sign {
	height: 440px;
	:deep(.elesigncode-vue) {
		background: #fff;
		height: calc(100% - 120px) !important;
		width: 100vw !important;
	}
	.btns {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 0 32px;
		background: #fff;
		border-top: 2px solid var(--border-color);
		box-sizing: border-box;
		height: 120px;
		div {
			height: 70px;
			line-height: 66px;
			width: 160px;
			box-sizing: border-box;
			border: 2px solid var(--van-primary-color);
			color: var(--van-primary-color);
			text-align: center;
			border-radius: 35px;
			font-size: 32px;
			margin-left: 12px;
			&:nth-of-type(2) {
				background: var(--van-primary-color);
				color: #fff;
			}
		}
	}
}
</style>
